//
//  BKUserFeedbackController.m
//  bestkeep
//
//  Created by windCould on 16/11/9.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserFeedbackController.h"
#import "BKCusTextView.h"
#import "BKMyCommon.h"
#import "BKShowImgCollectionView.h"
#import "BKEditPhotoController.h"
#import "BKLayoutImgCollectionViewCell.h"
#import "TZImagePickerController.h"
#import "BKUserUnitRequestAPI.h"
#import "BKUserMobileConfigInfo.h"

@interface BKUserFeedbackController ()<BKCusTextViewDelegate,BKShowImgCollectionViewDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate>

@property (nonatomic,strong)BKCusTextView * feedBackTextView;
@property (nonatomic,strong)BKShowImgCollectionView * imgCollectionView;
@property (nonatomic,strong)UILabel * tipLabel;

@property (nonatomic,strong)NSArray * imgArr;
@property (nonatomic,strong)NSMutableArray * dataImgArr; // 用于展示collectionView刷新
@property (nonatomic,strong)NSMutableArray * imgDataUrl; //上传图片后返回的服务器图片地址
@property (nonatomic,strong)NSString * feedBackStr;

@end


@implementation BKUserFeedbackController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = BKMyLocalizedString(@"BKUserFeedback");
    self.view.backgroundColor = ThemeBackgroundColor;
    self.dataImgArr = [NSMutableArray new];
    self.imgDataUrl = [NSMutableArray new];
    [self setUpViews];
    
    //添加手势 回退键盘
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapExitKeyboard)];
    tap.delegate = self;
    
    [self.view addGestureRecognizer:tap];
    
}

-(NSArray *)imgArr
{
    if (_imgArr == nil) {
        
         UIImage * img = [UIImage imageNamed:@"BK_My_btn_addpho_feedback"];
        _imgArr = @[img];
    }
 
    return _imgArr;
}


-(void)setDataImgArr:(NSMutableArray *)dataImgArr
{
    _dataImgArr = dataImgArr;
    NSMutableArray * temArr = [NSMutableArray arrayWithArray:_dataImgArr];
    [temArr addObjectsFromArray:_imgArr];
    self.imgCollectionView.imgArr = temArr;
}

-(void)setFianlImgArr:(NSArray *)fianlImgArr
{
    _fianlImgArr = fianlImgArr;
    self.dataImgArr = [NSMutableArray arrayWithArray:fianlImgArr];
}


#pragma mark =========================NetRequest===================================
//上传
-(void)upload:(UIButton *)btn
{
    [self.view endEditing:YES];
    NSString * msg = [self isRightStyleWithContent:self.feedBackStr];
    if (msg) {
        
        [HUD showErrorMessage:msg];
        return;
    }
    if (self.imgDataUrl == nil || self.imgDataUrl.count == 0) {
        
        self.imgDataUrl = [NSMutableArray arrayWithObjects:@"", nil];
    }
    
    NSMutableDictionary * dataDict = [NSMutableDictionary dictionary];
    [dataDict setObject:[self.imgDataUrl componentsJoinedByString:@","] forKey:@"imgUrls"];
    [dataDict setObject:self.feedBackStr forKey:@"content"];
    [dataDict setObject:@"3" forKey:@"source_code"];
    [dataDict setObject:[[BKUserMobileConfigInfo alloc]init].version forKey:@"version"];

    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI upLoadFeedBackInfoWithParameterDict:dataDict resultBlock:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                [HUD showSuccessMessage:@"上传成功"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            } else {
               
                [HUD showErrorMessage:result.msg];
            }
            
        } else {
        
            //NSLog(@"网络请求失败");
            [HUD showErrorMessage:@"网络请求失败"];
        }
    }];
}

//上传照片
-(void)upLoadImgData:(NSData *)imageData imageName:(NSString *)imageName
{
   [BKIndicationView dismiss];
   [BKIndicationView showInView:self.view];
   [BKUserUnitRequestAPI upLoadFeedBackImgData:imageData resultBlock:^(id obj, NSError *error) {
      
       [BKIndicationView dismiss];
       if (obj) {
           
           BKUserRequestResultModel * result = obj;
           if ([result.success isEqualToString:@"1"]) {
               
               [self.imgDataUrl addObject: result.data];
           
           }
           
           NSLog(@"意见反馈上传图片%@",result.msg);
           
       } else {
       
           NSLog(@"意见反馈图片上传失败网络请求失败。。。。");
       }
       
   }];
}


#pragma mark ==========================function===================================
//检验输入内容
-(NSString *)isRightStyleWithContent:(NSString *)content
{
    if ([self isEmpty:content] || content.length == 0||IsNilString(content)) {
        
        return @"请输入反馈内容";
    }
    
    if (content.length > 100) {
        
        return @"反馈信息过长";
    }
    
    //特殊字符过滤
    NSString *passwordStandard = @"^[(0-9)|(\u4e00-\u9fa5)|(A-Za-z0-9\u4e00-\u9fa5)|(@)|(!)|(#)|(+)|(-)|(%)|(,)|(<)|(，)|(。)|(.)|(/)|(?)|(;)|(；)|(：)|(:)|({)|([)|(])|(})|(*)|(~)|(`)|(·)|(《)|(》)|(>)|(？)|(“)|(&)|(……)|(…)|(^)|( )|(！)|(')|(”)|($)|(￥)|(（)|(）)]+$";
    NSRegularExpression *regexpasswordStandard = [NSRegularExpression regularExpressionWithPattern:passwordStandard options:0 error:nil];
    NSTextCheckingResult *isMatchpasswordStandard = [regexpasswordStandard firstMatchInString:content options:0 range:NSMakeRange(0,[content length])];
    if (!isMatchpasswordStandard) {
       
         return  @"不能输入特殊字符";
    }
    
    return nil;
    
}


//判断内容是否全部为空格  yes 全部为空格  no 不是
- (BOOL)isEmpty:(NSString *) str {
    
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

//输入内容时，textview的代理方法
-(void)customTextview:(BKCusTextView *)textview endEditingWithContent:(NSString *)content
{
    self.feedBackStr = content;
}

//回退键盘
-(void)tapExitKeyboard
{
    [self.feedBackTextView resignFirstResponder];
}


//添加图片
-(void)addImgFromPictureLibrary
{
    if (iOSSyStem >= 8.0) {
        
         UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [self takePhotoSelectImgWithSourceType:UIImagePickerControllerSourceTypeCamera];
            }];
            
            [alert addAction:action1];
        }

        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self selectImgFromPhotoLibraryMaxImagesCount:3-self.dataImgArr.count];
        }];
        
        UIAlertAction *cancelAction =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction:action2];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    
    } else {
        
        UIActionSheet * actionSheet;
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选取", nil];
            [sheet showInView:self.view];
        } else {
        
            UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册中选取", nil];
            [sheet showInView:self.view];
        }
        
        [actionSheet showInView:self.view];
    }
    
    
    
}

#pragma mark =========================选择照片的代理===================================

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerControllerSourceType  surcetype = UIImagePickerControllerSourceTypePhotoLibrary;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        switch (buttonIndex) {
            case 0:{
                
                surcetype = UIImagePickerControllerSourceTypeCamera;
                break;
            }
            case 1:{
                
                surcetype = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            }
                
            default:
                break;
        }
        
    } else {
    
        if (buttonIndex == 1) {
            
            surcetype = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        } else {
        
            return;
        }
    }
    
    [self takePhotoSelectImgWithSourceType:surcetype];

}

-(void)takePhotoSelectImgWithSourceType:(UIImagePickerControllerSourceType)surceType
{
    UIImagePickerController *imagePickerController =[[UIImagePickerController alloc]init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.navigationBar.barTintColor = [UIColor whiteColor];
    imagePickerController.sourceType = surceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

-(void)selectImgFromPhotoLibraryMaxImagesCount:(NSInteger)maxImgesCount
{
    TZImagePickerController *imgPickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:maxImgesCount delegate:self];
    [imgPickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL result) {
    
        for (UIImage *image in photos)
        {
            if (self.dataImgArr.count > 3) {
               
                break;
            }
            [self dealWithImg:image];
        }
        
        self.dataImgArr = self.dataImgArr;
    }];
    [self presentViewController:imgPickerVc animated:YES completion:nil];

}

-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
    
}

- (void)dealWithImg:(UIImage *)image{
    
    CGSize imageSize = image.size;
    imageSize.width = image.size.width / 2;
    imageSize.height = image.size.height / 2;
    CGFloat compressionQuality;
    
    if(image.size.height > 3000 || image.size.width > 3000) {
        compressionQuality = 0.3;
    } else if (image.size.height > 1500 || image.size.width > 1500){
        compressionQuality = 0.5;
    } else {
        compressionQuality = 0.8;
    }
    
    UIImage * img = [self imageWithImage:image scaledToSize:imageSize];
    NSData  * data = UIImageJPEGRepresentation(img, compressionQuality);
    
    if (self.dataImgArr.count <= 3) {
        
        [self upLoadImgData:data imageName:nil];
    }
    [self.dataImgArr addObject:img];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
   
    UIImage *icon = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dealWithImg:icon];
     self.dataImgArr = self.dataImgArr;
    UIImageWriteToSavedPhotosAlbum(icon,nil,nil,nil);
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark =========================BKShowImgCollectionViewDelegate============

-(void)showImgCollectionView:(BKShowImgCollectionView *)collectionView selectIndex:(NSInteger)index
{
   
        if (_dataImgArr.count == 0 || _dataImgArr.count == index) {
            
            [self addImgFromPictureLibrary];
        
        } else {
        
            __weak typeof(self) weakSelf = self;
            
            BKEditPhotoController * editPhotoVC = [[BKEditPhotoController alloc]init];

            editPhotoVC.imgShowArr = self.dataImgArr;
            editPhotoVC.curIndex = index;
            editPhotoVC.superController = self;
            editPhotoVC.deleteBlock = ^(NSInteger index){
            
                dispatch_async(dispatch_get_main_queue(), ^{
                   
                    [weakSelf.imgDataUrl removeObjectAtIndex:index];
                    
                });
                
                
            };
            
            [self presentViewController:editPhotoVC animated:YES completion:nil];
        }
        
}

#pragma mark =========================UIGestureRecognizerDelegate=================

//防止tap 手势 导致collectionView item 点击不响应的问题
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    NSLog(@"%@",NSStringFromClass([touch.view.superview class]));
    
    if ([NSStringFromClass([touch.view.superview class]) isEqualToString:@"BKLayoutImgCollectionViewCell"]) {
        
        return NO;
    } else {
    
        return YES;
    }

}


#pragma mark ============================布局======================================

-(void)setUpViews{

    UIButton *rightBt = [UIButton buttonWithType:UIButtonTypeCustom ];
    rightBt.frame = CGRectMake(0, 0, 40, 40);
    rightBt.titleLabel.font = UIFontCustom(15);
    [rightBt setTitle:@"提交" forState:UIControlStateNormal];
    [rightBt addTarget:self action:@selector(upload:) forControlEvents:UIControlEventTouchUpInside];
    [rightBt setTitleColor:RGBCOLOR(0, 186, 156, 1) forState:UIControlStateNormal];
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:rightBt];
    self.navigationItem.rightBarButtonItem = barItem;
 
    _feedBackTextView = [[BKCusTextView alloc]initWithFrame:CGRectZero];
    _feedBackTextView.backgroundColor = [UIColor whiteColor];
    _feedBackTextView.textDelegate = self;
    _feedBackTextView.font = [UIFont systemFontOfSize:13];
    _feedBackTextView.placeHolderString = @"请输入您的意见或建议，以帮助我们更好的改进产品。";
//    _feedBackTextView.layer.cornerRadius = 3;
//    _feedBackTextView.layer.masksToBounds = YES;
    _feedBackTextView.textDelegate = self;
    [self.view addSubview:_feedBackTextView];
    
    _imgCollectionView = [[BKShowImgCollectionView alloc]initWithFrame:CGRectZero];
    _imgCollectionView.backgroundColor = [UIColor cyanColor];
    _imgCollectionView.isDataOfImg = YES;
    _imgCollectionView.myDelegate = self;
    _imgCollectionView.imgArr = self.imgArr;
    _imgCollectionView.collectionView.scrollEnabled = NO;
    _imgCollectionView.itemSize = CGSizeMake(85, 85);
    [self.view addSubview:_imgCollectionView];
   
    
    _tipLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _tipLabel.text = @"＊针对操作时遇到的问题可选择截图提供给我们，我们会及时进行调整 （图片最多可上传3张）";
    _tipLabel.backgroundColor = [UIColor clearColor];
    _tipLabel.textColor = HexColor(0x888888);
    _tipLabel.numberOfLines = 0;
    _tipLabel.font = UIFontCustom(12);
    [self.view addSubview:_tipLabel];
    
    [self layoutViews];
    
}


-(void)layoutViews{

    [_feedBackTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view.mas_top).offset(10);
        make.left.mas_equalTo(self.view.mas_left).offset(ApplicationBackGauge);
        make.right.mas_equalTo(self.view.mas_right).offset(-ApplicationBackGauge);
        make.height.mas_equalTo(@(155));
    }];
    
    [_imgCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_feedBackTextView.mas_bottom).offset(10);
        make.left.mas_equalTo(self.view.mas_left).offset(ApplicationBackGauge);
        make.right.mas_equalTo(self.view.mas_right).offset(-ApplicationBackGauge);
        make.height.mas_equalTo(@(85));
    }];
    
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_imgCollectionView.mas_bottom).offset(10);
        make.left.mas_equalTo(self.view.mas_left).offset(ApplicationBackGauge);
        make.right.mas_equalTo(self.view.mas_right).offset(-ApplicationBackGauge);
       
    }];
  
    
}




@end
